<style lang="less" scoped>
.img {
  width: 100%;
  height: 150px;
  overflow: hidden;
}

.lesson-props {
  .title {
    font-size: 24px;
  }
}

.btns {
  margin-top: 20px;
}
</style>

<template>
  <nut-navbar title="购买课程" left-show @click-back="router.back" />
  <div class="lesson-detail">
    <div class="img">
      <nut-image :src="cfg.imageUrl(store.lessonDetail?.thumb)" fit="cover" />
    </div>
    <div class="lesson-props">
      <div class="title">{{ store.lessonDetail?.title }}</div>
      <div class="expired"></div>
      <div class="price">
        <nut-price :price="store.lessonDetail?.price" size="large" /> &nbsp;&nbsp;
        <nut-price :price="store.lessonDetail?.marketPrice" size="normal" strike-through />
      </div>
    </div>
  </div>
  <div class="btns" style="text-align: center">
    <nut-button type="primary" @click="handleBuy">确认购买</nut-button>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useLessonStore } from '@/stores/lesson'
import { useOrderStore } from '@/stores/order'
import cfg from '@/config/config'
import { showToast } from '@nutui/nutui'

const store = useLessonStore()
const orderStore = useOrderStore()
const router = useRouter()
const route = useRoute()

onMounted(() => {
    console.log(store.lessonDetail)
  if (store.lessonDetail.id === 0) {
    console.log(route.params)
    if (route.params.id && route.params.id > 0) {
      store.loadDetail(parseInt(route.params.id as string))
    } else {
      router.back()
    }
  }
})

const handleBuy = async () => {
  const sn = await orderStore.create({
    lessonId: store.lessonDetail.id,
    price: store.lessonDetail.price
  })
  if (sn != '') {
    showToast.success('购买成功', {
      closeOnClickOverlay: true,
      onClose: () => {
        router.push({ name: 'my_order_detail', params: { sn } })
      }
    })
  } else {
    showToast.failed('购买失败')
  }
}
</script>
